rm(list = ls())
gc()
require(tidyverse)
require(labelled)
require(moments)
library(modelr)

################################################################################
##
## Date:    2024-12-22
## Author:  james.h.bisbee@vanderbilt.edu; zilinsky@nyu.edu
## Purpose: This script generates SI Figure 3.
## Inputs:  ./data/anonymized_figS3.RData
##            - Anonymized Gallup data
## Outputs: ./figures/figS3.pdf
##
################################################################################

# Compute details
print(paste0('Compute environment from ',Sys.Date(),' run by Bisbee'))
if(Sys.info()['sysname'] == 'Windows') {
  ram_size = system("wmic MemoryChip get Capacity", intern = TRUE)[-1]
  model_name = system("wmic cpu get name", intern = TRUE)[2] # nocov
  vendor_id = system("wmic cpu get manufacturer", intern = TRUE)[2] # nocov
  
  print(list(ram = stringr::str_squish(ram_size)[1],
             vendor_id = stringr::str_squish(vendor_id),
             model_name = stringr::str_squish(model_name),
             no_of_cores = parallel::detectCores()))
} else if(Sys.info()['sysname'] == 'Linuxs') {
  splitted <- strsplit(system("ps -C rsession -o %cpu,%mem,pid,cmd", intern = TRUE), " ")
  df <- do.call(rbind, lapply(splitted[-1], 
                              function(x) data.frame(
                                cpu = as.numeric(x[2]),
                                mem = as.numeric(x[4]),
                                pid = as.numeric(x[5]),
                                cmd = paste(x[-c(1:5)], collapse = " "))))
  df
} else {
  cat("If not on Linux or Windows, you'll have to figure out your own solution to seeing the compute environment.")
}

sessionInfo()

load('./data/anonymized_figS3.RData')

getPCP <- function(x) {
  DAMisc::pre(x)$pcp %>% round(3) *100
}

getePRE <- function(x) {
  tmp <- DAMisc::pre(x)
  res <- tmp$epre
  names(res) <- tmp$m1form
  return(res)
}

logit_bivariate <- function(depvar) {
  glm(paste0(depvar, " ~ copartisan"), family = binomial,data = dat)
}

models <- map(DVsBIN, logit_bivariate)

# % correctly predicted is misleading, b/c these models can do "well" by always 
# predicting the modal value; but let's see
# install.packages('DAMisc')
# devtools::install_github('https://github.com/davidaarmstrong/damisc')

#############################################################################
# xpected proportional reduction in error is presumably the way to go
#############################################################################
ePRE <- sapply(models,function(x) getePRE(x)) %>%
  enframe()

toplot <- ePRE %>% 
  slice(-10) %>% # Get rid of the VA governor question
  mutate(outcome = c("Do you approve or disapprove of the way\nDonald Trump is handling his job as president?",
                     "Have there been times in the past twelve months when you did not\nhave enough money to buy food that you or your family needed?",
                     "Do you have a favorable or unfavorable opinion of\nHillary Clinton, or haven't you heard of them?",
                     "Are you satisfied or dissatisfied with your standard\nof living, all the things you can buy and do?",
                     "Did you experience the following feelings\nduring a lot of the day yesterday? Worry",
                     "Did you experience the following feelings\nduring a lot of the day yesterday? Sadness",
                     "Did you experience the following feelings\nduring a lot of the day yesterday? Stress",
                     "Did you experience the following feelings\nduring a lot of the day yesterday? Happiness",
                     "Do you approve or disapprove of the way\nBarack Obama is handling his job as president?",
                     "How would you rate economic\nconditions in this country today?",
                     "Right now, do you think that economic conditions in this\ncountry, as a whole, are getting better or getting worse?",
                     "Are you feeling better about your\nfinancial situation these days, or not?",
                     "[AGREE/DIS] You are watching your\nspending very closely.",
                     "[AGREE/DIS] You have more than enough\nmoney to do what you want to do.",
                     "Did you worry yesterday that you\nspent too much money, or not?",
                     "Are you feeling pretty good these days about the\namount of money you have to spend, or not?",
                     "At this time, are you cutting back on how\nmuch money you spend each week, or not?",
                     "Would you be able right now to make a major purchase, such as a car,\nappliance, or furniture, or pay for a significant home repair if you needed to?"))

pdf('./figures/figS3.pdf',width = 8,height = 7)
toplot %>%
  ggplot(aes(x=value,
             y=fct_reorder(outcome,value))) +
  geom_segment(aes(x=0,xend=value,
                   y=fct_reorder(outcome,value),
                   yend=fct_reorder(outcome,value),)) +
  geom_point(size=2.5) +
  labs(x="Expected proportional reduction in error",
       title = "Y = f(copartisan with the sitting president)",subtitle = "Logit models",
       color = 'ePre',
       y="Outcome variable") +
  theme_bw() + 
  theme(legend.position = 'none')
dev.off()

# EOF